package edu.uwosh.cs342.project4;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import edu.uwosh.cs342.project4.model.Place;

public class Project4Activity extends MapActivity {
	
	private int minMillisecondThresholdForLongClick = 800;
	private long startTimeForLongClick = 0;
	private float xScreenCoordinateForLongClick;
	private float yScreenCoordinateForLongClick;
	private float xtolerance=10;//x pixels that your finger can be off but still constitute a long press
	private float ytolerance=10;//y pixels that your finger can be off but still constitute a long press
	private float xlow; //actual screen coordinate when you subtract the tolerance
	private float xhigh; //actual screen coordinate when you add the tolerance
	private float ylow; //actual screen coordinate when you subtract the tolerance
	private float yhigh; //actual screen coordinate when you add the tolerance


	private MapController mapController;
	private MapView mapView;
	GeoPoint p;
	myItemizedOverlay itemizedoverlay;
	boolean hasResumed = false;
	List<Overlay> mapOverlays;
	CharSequence[] F_NAMES;
	GeoPoint currentPoint;
	SQLiteDatabase favDBQuery;
	DBHelper dbh;

	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		setContentView(R.layout.main); // bind the layout to the activity
		final Context context = this.getBaseContext();
		// Configure the Map
		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		mapView.setSatellite(true);
		mapController = mapView.getController();
		mapController.setZoom(7); // Zoom 1 is world view
		String coordinates[] = { "44.261870", "-88.415390" };
		double lat = Double.parseDouble(coordinates[0]);
		double lng = Double.parseDouble(coordinates[1]);

		p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
		currentPoint = p;

		mapController.animateTo(p);
		mapView.invalidate();

		// create Criteria object to specify location provider's settings
		Criteria criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_FINE); // fine location data
		criteria.setBearingRequired(true); // need bearing to rotate map
		criteria.setCostAllowed(true); // OK to incur monetary cost
		criteria.setPowerRequirement(Criteria.POWER_LOW); // try to conserve
		criteria.setAltitudeRequired(false); // don't need altitude data
		// get the LocationManager
		LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
		String provider = locationManager.getBestProvider(criteria, true);
		locationManager.getProvider(LocationManager.GPS_PROVIDER);
		// Gives you a location provider object

		GeoUpdateHandler locationListener = new GeoUpdateHandler();
		// listen for changes in location as often as possible
		locationManager
				.requestLocationUpdates(provider, 0, 0, locationListener);
		mapOverlays = mapView.getOverlays();
		Drawable drawable = this.getResources().getDrawable(
				R.drawable.ic_maps_indicator_current_position);
		itemizedoverlay  = new myItemizedOverlay(drawable, this);

		OverlayItem overlayitem = new OverlayItem(p, "Hola, Mundo!",
				"This is your current location"); 

		itemizedoverlay.addOverlay(overlayitem);
		mapOverlays.add(itemizedoverlay);
		

		// SearchSrv srv = new SearchSrv();
		// setProgressBarIndeterminateVisibility(true);
		// srv.execute();
	}
	
	@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int actionType = ev.getAction();
        if (actionType == MotionEvent.ACTION_DOWN) {
            startTimeForLongClick=ev.getEventTime();
        } 
        else if (actionType == MotionEvent.ACTION_UP) {
            long eventTime = ev.getEventTime();
            long downTime = ev.getDownTime(); 
            if (startTimeForLongClick==downTime){ 
                if ((eventTime-startTimeForLongClick)>minMillisecondThresholdForLongClick){ 
                        GeoPoint p = mapView.getProjection().fromPixels(
            	                (int) ev.getX(),
            	                (int) ev.getY());
            			 		Intent addFav = new Intent(mapView.getContext(),
            					AddFavActivity.class);
            			 		addFav.putExtra("lat", p.getLatitudeE6());
            			 		addFav.putExtra("lng", p.getLongitudeE6());
            			 		mapView.getContext().startActivity(addFav);
                }
            }

        }


        return super.dispatchTouchEvent(ev);
    }

	

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	public class GeoUpdateHandler implements LocationListener {

		public void onLocationChanged(Location location) {
			int lat = (int) (location.getLatitude() * 1E6);
			int lng = (int) (location.getLongitude() * 1E6);
			GeoPoint point = new GeoPoint(lat, lng);
			currentPoint = point;
			mapController.animateTo(point); // mapController.setCenter(point);
			OverlayItem overlayitem = new OverlayItem(point, "You are Here!",
					"This is your current location");
			itemizedoverlay.addOverlay(overlayitem);

		}

		public void onProviderDisabled(String provider) {
		}

		public void onProviderEnabled(String provider) {
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (getIntent().hasExtra("lat")) {

			double lati = getIntent().getDoubleExtra("lat", 0.0);
			double lngi = getIntent().getDoubleExtra("lon", 0.0);
			p = new GeoPoint((int) (lati * 1E6),
					(int) (lngi * 1E6));
			currentPoint = p;
			mapController.animateTo(p);
			OverlayItem newOverlayitem = new OverlayItem(p,	"Hola, Mundo!", "This is your current location");
			itemizedoverlay.addOverlay(newOverlayitem);
		}
	}

	@Override
	protected void onPause() {
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.favorites:

			List<String> names = new ArrayList<String>();
			dbh = new DBHelper(this);
			favDBQuery = dbh.getReadableDatabase();

			String select = "select name from favorites";
			Cursor cursor = favDBQuery.rawQuery(select, null);

			if (cursor.moveToFirst()) {
				do{
					int dbNameIndex = cursor.getColumnIndex("name");
					String dbName = cursor.getString(dbNameIndex);
					names.add(dbName);
				}while(cursor.moveToNext());
			}
	
			cursor.close();
			
			final CharSequence[] items = names.toArray(new CharSequence[names.size()]);
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Favorites");
			builder.setSingleChoiceItems(items, -1,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int item) {
							String selectLat = "select lat from favorites where name = '" + items[item] +"'";
							String selectLong = "select long from favorites where name = '" + items[item]+"'";
							
							Cursor cursor = favDBQuery.rawQuery(selectLat, null);
							cursor.moveToFirst();
							int dbNameIndex = cursor.getColumnIndex("lat");
							double lati = cursor.getDouble(dbNameIndex);
							cursor.close();
							
							cursor = favDBQuery.rawQuery(selectLong, null);
							cursor.moveToFirst();
							dbNameIndex = cursor.getColumnIndex("long");
							double longi = cursor.getDouble(dbNameIndex);
							cursor.close();
							
							//Toast.makeText(getApplicationContext(), "Lat: "+lati+" Long: "+longi, Toast.LENGTH_SHORT).show();
							
							GeoPoint point = new GeoPoint((int)(lati), (int)(longi));
							currentPoint = point;
							mapController.animateTo(point); // mapController.setCenter(point);
							OverlayItem overlayitem = new OverlayItem(point, "You are Here!",
									"This is your current location");
							itemizedoverlay.addOverlay(overlayitem);
							mapController.setZoom(10); 
							//Toast.makeText(getApplicationContext(), "Lat: "+lati+" Long: "+longi, Toast.LENGTH_SHORT).show();
							dialog.dismiss();
						}
					});
			AlertDialog alert = builder.create();
			alert.show();
			return true;
		case R.id.search:
			// bring up menu
			Intent manualIntent = new Intent(Project4Activity.this,
					ManualCoordsActivity.class);
			startActivity(manualIntent);
			hasResumed = true;
			return true;
		case R.id.add:
			// go to add page
			Intent addIntent = new Intent(Project4Activity.this,
					AddFavActivity.class);
			addIntent.putExtra("lat", currentPoint.getLatitudeE6());
			addIntent.putExtra("lng", currentPoint.getLongitudeE6());
			startActivity(addIntent);
			return true;
			
		case R.id.nearby:
			PlaceRequest placeRequest = new PlaceRequest(p.getLatitudeE6()/ 1E6, p.getLongitudeE6()/ 1E6);
			ArrayList <Place> placesArray= new ArrayList<Place>();
			try {
				placesArray = placeRequest.performSearch();
			} catch (Exception e) {
				Log.d("error", "error getting place list");e.printStackTrace(); 
			}
			
			itemizedoverlay.addNearby(placesArray);
			
			mapController.setZoom(17); 
			
//			Toast.makeText(getApplicationContext(),
//					placesArray.get(0).getName(), Toast.LENGTH_SHORT).show();
			return true;
		case R.id.remove:

			List<String> removeNames = new ArrayList<String>();
			dbh = new DBHelper(this);
			favDBQuery = dbh.getReadableDatabase();

			String removeSelect = "select name from favorites";
			Cursor removeCursor = favDBQuery.rawQuery(removeSelect, null);

			if (removeCursor.moveToFirst()) {
				do{
					int dbNameIndex = removeCursor.getColumnIndex("name");
					String dbName = removeCursor.getString(dbNameIndex);
					removeNames.add(dbName);
				}while(removeCursor.moveToNext());
			}
	
			removeCursor.close();
			
			final CharSequence[] removeItems = removeNames.toArray(new CharSequence[removeNames.size()]);
			AlertDialog.Builder removeBuilder = new AlertDialog.Builder(this);
			removeBuilder.setTitle("Favorites");
			removeBuilder.setSingleChoiceItems(removeItems, -1,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int item) {
							favDBQuery.delete("favorites", "name = '" + removeItems[item] + "'", null);
							dialog.dismiss();
						}
					});
			AlertDialog removeAlert = removeBuilder.create();
			removeAlert.show();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
